var ErrorMessage = [];
var PointSale = {
    cityId : '0'
};
var phoneCodePrefix = "cp";
var isImageVerificationSkipped = false;
var isTermSkipped = false;


var CurrentPosition = {
    lat : 21.022902,
    lng : 105.852453
};

var LanguageConst = {
    _MSG_POINT_SALE_NOT_EMPTY : "",
    _MSG_STREET_NOT_EMPTY : "",
    _MSG_INVALID_EMAIL : "",
    _MSG_INVALID_POSITION : "",
    _MSG_INVALID_PHONE:"",
    _MSG_CITY_NOT_EXIST:"",
    _MSG_COUNTRY_NOT_EXIST:"",
    _MSG_SUPPLIER_NOT_EXIST:"",
    _MSG_TERM_NOT_CHECKED:"",
    _MSG_IMAGE_VERIFICATION_NOT_EMPTY:"",
    _MSG_IMAGE_VERIFICATION_NOT_MATCH:""
};

var Const = {
    MAX_LENGTH_POINT_SALE_NAME : 0,
    MAX_LENGTH_LOCATION_ADDRESS : 0,
    MAX_LENGTH_EMAIL : 0,
    MAX_LENGTH_PHONE_NUMBER : 0
};

var Map = {
    map : null,
    geocoder :null,
    currentMarker:null,
    address:null,
    iconMarker:"http://www.celltreesinc.com/maps/icons/green-dot.png",
    
    onMarkerClicked:function(map,marker){},
    initMap:function() {
        var position = new google.maps.LatLng(CurrentPosition.lat,CurrentPosition.lng);
        var mapOptions = {
            center: position,
            zoom: 15,
            zIndex: null,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
     
        Map.geocoder = new google.maps.Geocoder();
        Map.map = new google.maps.Map(document.getElementById("map"), mapOptions);
        Map.createMarker(position);
        google.maps.event.addListener( Map.map , 'click', function(e) {
            Map.setCurrentMarker(e.latLng);
        });

    },
    
    setPoint:function(location){
        function codeAddress() {
            Map.geocoder.geocode( {
                'address':location
            }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    var latlng = results[0].geometry.location;
                    Map.map.setCenter(latlng);
                    Map.setCurrentMarker(latlng);
                } 
            }
            );
        }
        codeAddress();
        return true;
    },
    
    createMarker:function (position) {
        
        var marker = new google.maps.Marker({
            position: position,
            clickable: true,
            map: Map.map,
            icon: Map.iconMarker
        });
        Map.currentMarker = marker;
       
        google.maps.event.addListener(marker, 'click', function() {
            Map.onMarkerClicked(Map.map,marker);
        });
        return marker;
    },
    
    setCurrentMarker:function (position){
        Map.currentMarker.setMap(null);
        Map.createMarker(position);
    }
};


function showMessage(message,objField){
    var errorMessage = document.getElementById("error_message");
    while (errorMessage.firstChild) {
        errorMessage.removeChild(errorMessage.firstChild);
    }
    var container = document.createElement('div');
    container.innerHTML = message;
    errorMessage.appendChild(container);
}


function validatePointSaleForm(objForm){
    trimFieldValue(objForm.point_sale_name);
    trimFieldValue(objForm.address);
    trimFieldValue(objForm.phone);
    trimFieldValue(objForm.email);
    if(!isImageVerificationSkipped){
        trimFieldValue(objForm.captcha);
    }

    if(emptyField(objForm.point_sale_name)){
        showMessage(LanguageConst._MSG_POINT_SALE_NOT_EMPTY,objForm.point_sale_name);
        return false;
    }
    else if(!isValidLengthTextBox(objForm.point_sale_name,LanguageConst._MSG_OVER_MAX_LENGTH_ALLOW,LanguageConst._LB_NAME,Const.MAX_LENGTH_POINT_SALE_NAME)){
        return false;
    }
    else if(emptyField(objForm.address)){
        showMessage(LanguageConst._MSG_STREET_NOT_EMPTY,objForm.address);
        return false;
    }
    else if(!isValidLengthTextBox(objForm.address,LanguageConst._MSG_OVER_MAX_LENGTH_ALLOW,LanguageConst._LB_ADDRESS,Const.MAX_LENGTH_LOCATION_ADDRESS)){
        return false;
    }
    else if(objForm.email.value != "" && !isEmail(objForm.email.value)){
        showMessage(LanguageConst._MSG_INVALID_EMAIL,objForm.email);
        return false;
    }
    else if(!isValidLengthTextBox(objForm.email,LanguageConst._MSG_OVER_MAX_LENGTH_ALLOW,LanguageConst._LB_EMAIL,Const.MAX_LENGTH_EMAIL)){
        return false;
    }
    else if(objForm.phone.value != "" && !isPhone(objForm.phone.value)){
        showMessage(LanguageConst._MSG_INVALID_PHONE,objForm.phone);
        return false;
    }
    else if(!isValidLengthTextBox(objForm.phone,LanguageConst._MSG_OVER_MAX_LENGTH_ALLOW,LanguageConst._LB_PHONE,Const.MAX_LENGTH_PHONE_NUMBER)){
        return false;
    }
    else if(Map.currentMarker == null){
        showMessage(LanguageConst._MSG_INVALID_POSITION);
        return false;
    }
    else if(!isImageVerificationSkipped && emptyField(objForm.captcha)){
        showMessage(LanguageConst._MSG_IMAGE_VERIFICATION_NOT_EMPTY);
        return false;
    }
    else if(!isImageVerificationSkipped && objForm.captcha.value.toLowerCase() != objForm.temp_captcha.value.toLowerCase()){
        showMessage(LanguageConst._MSG_IMAGE_VERIFICATION_NOT_MATCH);
        return false;
    }
    else if(!isTermSkipped &&  !objForm.is_term.checked){
        showMessage(LanguageConst._MSG_TERM_NOT_CHECKED);
        return false;
    }
  
    //build Position 
    var position = document.getElementById("position");
    var location = Map.currentMarker.getPosition();
    position.value = location.lat()+","+location.lng();
    
    return true;
} 

function loadCity(){
    removeOption("city");
    var city = document.getElementById("city");
    city.disabled = true;
    var countryId = document.getElementById("country").value;
    var url = "/point-sale-form/getCity";
    var params = new Array();
    params["country_id"] = countryId;
    var result = Ajax.callFunction(url, params);
    for(var i=0;i<result.length;i++){
        addOption(city,result[i].NAME,result[i].ID,PointSale.cityId);
    }
    city.disabled = false;
}

function locationAddress(){
    var psName = document.getElementById("point_sale_name");
    var address = document.getElementById("address");
    trimFieldValue(address);
    trimFieldValue(psName);
    if(address.value != ""){
        Map.setPoint(address.value);
    }
}

function loadErrorMessage(){
    var errorMessage = document.getElementById("error_message");
    for (var key in ErrorMessage) {
        var container = document.createElement('div');
        container.innerHTML = ErrorMessage[key];
        errorMessage.appendChild(container);
    }
}

function loadMapSize(){
    var region  = document.getElementById("region");
    var map  = document.getElementById("map");
    var bodyHeight = getBodyHeight();
    var bodyWidth = getBodyWidth();
    var navigationWidth = getWidth("navigation");
    var pointSaleFormWidth = getWidth("point_sale_form");
    region.style.height =   (bodyHeight) +"px";
    region.style.width =   (bodyWidth-navigationWidth-pointSaleFormWidth) +"px";
    map.style.height  = region.style.height;
}

function refreshCaptcha(){
    var url = "/point-sale-form/getCaptcha";
    var result = Ajax.callFunction(url, null);
    if(result != null && result.length == 2){
        var temp_captcha = result[0];
        var temp_captcha_url = result[1];
        document.getElementById("temp_captcha").value = temp_captcha;
        document.getElementById("image_verification").src = temp_captcha_url;
    }
}

function loadPhoneCode(){
    var phoneCode =  document.getElementById("phone_code");
    var phoneCodeCotainer = document.getElementById("phone_code_symbol");
    phoneCodeCotainer.className = phoneCodePrefix + phoneCode.value;
    
}

//Override
Page.load = function(){
    Navigation.hide();
    loadCity();
    loadErrorMessage();
    loadPhoneCode();
    Panel.show();
    loadMapSize();
};

Map.onMarkerClicked = function(map,marker){
    var psName = document.getElementById("point_sale_name");
    trimFieldValue(psName);
    if(psName.value != ""){
        info = new google.maps.InfoWindow({
            content:'<div>'+psName.value+'</div>'
        });
        info.open(map,marker);
    }
}

Setting.onSettingMouseOver = function(objMe){
    var map  = document.getElementById("region");
    map.style.zIndex = -1;
}

Setting.onSettingMouseOut = function(objMe){
    var map  = document.getElementById("region");
    map.style.zIndex = 0;
}

Page.resize = function(){
    loadMapSize();
}
